package com.astar.service.impl;

import com.astar.enums.EmailMessageType;
import com.astar.service.SendMailService;
import com.astar.utils.Constant;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.email.EmailPopulatingBuilder;
import org.simplejavamail.mailer.Mailer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.activation.FileDataSource;
import java.io.File;
import java.util.List;
import java.util.Map;


/**
 * Created by liuruiyan on 2019/04/12.
 */
@Service
public class SendMailServiceImpl implements SendMailService {

    @Value("${mail.server.from.user:''}")
    private String fromName;

    @Value("${mail.server.from.email:''}")
    private String fromEmail;

    @Autowired
    private Mailer simpleJavaMail;

    /**
     *  发送邮件
     * @param toRecipientName 收件人姓名
     * @param toRecipientAddress 收件人邮箱
     * @param listCCRecipients 抄送人列表   Map   key：name （收件人名称）   key：mailAddress（邮件地址）
     * @param mailSubject 主题
     * @param mailContent 正文
     * @return
     */
    @Override
    public boolean sendMail(String toRecipientName, String toRecipientAddress, List<Map<String, String>> listCCRecipients, String mailSubject, String mailContent,String messageType) {
        boolean bool = true;

        EmailPopulatingBuilder builder = EmailBuilder.startingBlank()
                .from(fromName, fromEmail) //发件人
                .to(toRecipientName, toRecipientAddress)    //收件人
                .withSubject(mailSubject);

        if(EmailMessageType.HTML.getCode().equals(messageType)){
            builder.withHTMLText(mailContent);
        }else{
            builder.withPlainText(mailContent);
        }


        if(listCCRecipients!=null && listCCRecipients.size()>0){
            for (Map<String,String > map01: listCCRecipients) {
                builder.cc(map01.get(Constant.SEND_MAIL_CC_RECIPIENTS_NAME),map01.get(Constant.SEND_MAIL_CC_RECIPIENTS_ADDRESS));
            }
        }


        try {
            simpleJavaMail.sendMail(builder.buildEmail());
        } catch (Exception e) {
            bool = false;
            e.printStackTrace();
        }

        return bool;
    }

    /**
     *  发送邮件
     * @param listTORecipients    收件人列表   Map   key：name （收件人名称）   key：mailAddress（邮件地址）
     * @param listCCRecipients    抄送人列表   Map   key：name （收件人名称）   key：mailAddress（邮件地址）
     * @param mailSubject       邮件主题
     * @param mailContent       邮件正文
     * @return
     */
    @Override
    public boolean sendMail(List<Map<String, String>> listTORecipients, List<Map<String, String>> listCCRecipients, String mailSubject, String mailContent,String messageType) {
        boolean bool = true;

        EmailPopulatingBuilder builder = EmailBuilder.startingBlank()
                .from(fromName, fromEmail) //发件人
                .withSubject(mailSubject);

        if(EmailMessageType.HTML.getCode().equals(messageType)){
            builder.withHTMLText(mailContent);
        }else{
            builder.withPlainText(mailContent);
        }

        if(listTORecipients!=null && listTORecipients.size()>0){

            for (Map<String,String > map: listTORecipients) {
                builder.to(map.get(Constant.SEND_MAIL_TO_RECIPIENTS_NAME), map.get(Constant.SEND_MAIL_TO_RECIPIENTS_ADDRESS));
            }

            if(listCCRecipients!=null && listCCRecipients.size()>0){
                for (Map<String,String > map01: listCCRecipients) {
                    builder.cc(map01.get(Constant.SEND_MAIL_CC_RECIPIENTS_NAME), map01.get(Constant.SEND_MAIL_CC_RECIPIENTS_ADDRESS));
                }
            }

            try {
                simpleJavaMail.sendMail(builder.buildEmail());
            } catch (Exception e) {
                bool = false;
                e.printStackTrace();
            }

        }else{
            bool = false;
        }

        return bool;
    }


    /**
     *  发送邮件,包括附件信息
     * @param listTORecipients    收件人列表   Map   key：name （收件人名称）   key：mailAddress（邮件地址）
     * @param listCCRecipients       抄送人列表   Map   key：name （收件人名称）   key：mailAddress（邮件地址）
     * @param mailSubject       邮件主题
     * @param mailContent       邮件正文
     * @param attachmentName    附件名
     * @param attachmentPath    附件绝对路径
     * @return boolean
     */
    @Override
    public boolean sendMail(List<Map<String, String>> listTORecipients, List<Map<String, String>> listCCRecipients, String mailSubject, String mailContent,String messageType, String attachmentName, String attachmentPath) {
        boolean bool = true;


        EmailPopulatingBuilder builder = EmailBuilder.startingBlank()
                .from(fromName, fromEmail) //发件人
                .withSubject(mailSubject);

        if(EmailMessageType.HTML.getCode().equals(messageType)){
            builder.withHTMLText(mailContent);
        }else{
            builder.withPlainText(mailContent);
        }


        if(listTORecipients!=null && listTORecipients.size()>0){

            for (Map<String,String > map: listTORecipients) {
                builder.to(map.get(Constant.SEND_MAIL_TO_RECIPIENTS_NAME), map.get(Constant.SEND_MAIL_TO_RECIPIENTS_ADDRESS));
            }

            if(listCCRecipients!=null && listCCRecipients.size()>0){
                for (Map<String,String > map01: listCCRecipients) {
                    builder.cc(map01.get(Constant.SEND_MAIL_CC_RECIPIENTS_NAME), map01.get(Constant.SEND_MAIL_CC_RECIPIENTS_ADDRESS));
                }
            }

            //判断附件是否存在
            File file = new File(attachmentPath);
            if(file.exists()){

                System.setProperty("mail.mime.splitlongparameters","false");//防止附件名乱码
                builder.withAttachment(attachmentName,new FileDataSource(attachmentName));

                try {
                    simpleJavaMail.sendMail(builder.buildEmail());
                } catch (Exception e) {
                    bool = false;
                    e.printStackTrace();
                }
            }else{
                bool = false;
            }

        }else{
            bool = false;
        }

        return bool;
    }
}
